import os
import os.path
import threading
import tkinter
import tkinter.messagebox
import tkinter.simpledialog

from GetDrivers import GetDrivers

rubbihExt = ['.tmp', '.bak', '.old', '.wbk', '.xlk', '.mp', '.log', '.gid', '.chk', '.syd', '.$$$', '.@@@', '.~*']


class Window:
    def __init__(self):
        self.root = tkinter.Tk()

        # 创建菜单
        menu = tkinter.Menu(self.root)

        # 创建"系统子菜单"
        submenu = tkinter.Menu(menu, tearoff=0)
        submenu.add_command(label="关于...", command=self.MenuAbout)
        submenu.add_separator()
        submenu.add_command(label="退出", command=self.MeunExit)
        menu.add_cascade(label="系统", menu=submenu)

        # 创建“清理” 子菜单
        submenu = tkinter.Menu(menu, tearoff=0)
        submenu.add_command(label="扫描垃圾文件", command=self.MenuScanRubbish)
        submenu.add_command(label="删除垃圾文件", command=self.MenuDelRubbish)
        menu.add_cascade(label="清理", menu=submenu)

        # 创建“查找” 子菜单
        submenu = tkinter.Menu(menu, tearoff=0)
        submenu.add_command(label="搜索大文件", command=self.MenuScanBigFile)
        submenu.add_separator()
        submenu.add_command(label="按名称搜索文件", command=self.MenuSearchFile)
        menu.add_cascade(label="搜索", menu=submenu)

        self.root.config(menu=menu)

        # 创建标签用于显示状态信息
        self.progress = tkinter.Label(self.root, anchor=tkinter.W, text="状态", bitmap='hourglass', compound='left')
        self.progress.place(x=10, y=370, width=480, height=15)

        # 创建文本框，显示文件列表
        self.flist = tkinter.Text(self.root)
        self.flist.place(x=10, y=10, width=480, height=350)

        # 为文本框添加垂直滚动条
        self.vscroll = tkinter.Scrollbar(self.flist)
        self.vscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.flist['yscrollcommand'] = self.vscroll.set
        self.vscroll.config(command=self.flist.yview)

    def MainLoop(self):
        self.root.title("Findfat")
        self.root.minsize(500, 400)
        self.root.maxsize(500, 400)
        self.root.mainloop()

    # 关于菜单
    def MenuAbout(self):
        tkinter.messagebox.showinfo("About", "Findfat v0.1");

    # 退出菜单
    def MeunExit(self):
        self.root.quit()

    # 扫描垃圾文件 菜单
    def MenuScanRubbish(self):
        result = tkinter.messagebox.askquestion("ScanRubbish", "扫描垃圾文件将需要较长的时间,是否继续？")
        if result == "no":
            return
        tkinter.messagebox.showinfo("ScanRubbish", "马上开始扫描垃圾文件")
        self.drivers = GetDrivers()
        t = threading.Thread(target=self.ScanRubbish, args=(self.drivers,))
        t.start()

    def MenuDelRubbish(self):
        result = tkinter.messagebox.askquestion("DelRubbish", "删除垃圾文件将需要较长的时间,是否继续？")
        if result == "no":
            return
        tkinter.messagebox.showinfo("DelRubbish", "马上开始删除垃圾文件")
        self.drivers = GetDrivers()
        t = threading.Thread(target=self.DeleteRubbish, args=(self.drivers,))
        t.start()

    def MenuScanBigFile(self):
        s = tkinter.simpledialog.askinteger('ScanBigFile', '请设置大文件的大小(M)')
        t = threading.Thread(target=self.ScanBigFile, args=(s,))
        t.start()

    def MenuSearchFile(self):
        result = tkinter.messagebox.askquestion("SearchFile", "按名称搜索大文件将需要较长的时间,是否继续？")
        if result == "no":
            return
        tkinter.messagebox.showinfo("SearchFile", "马上开始按名称搜索大文件")

    def ScanBigFile(self, filesize):
        total = 0
        filesize = filesize * 1024 * 1024
        for driver in GetDrivers():
            for root, dirs, files in os.walk(driver):
                for fil in files:
                    try:
                        fname = os.path.abspath(os.path.join(root, fil))
                        fsize = os.path.getsize(fname)
                        self.progress['text'] = fname
                        if fsize >= filesize:
                            total += 1
                            self.flist.insert(tkinter.END, '%s,[%.2f M]\n' % (fname, fsize / 1024 / 1024))
                    except:
                        pass
        self.progress['text'] = "找到 %s 个超过 %s M大文件" % (total, filesize / 1024 / 1024)

    def DeleteRubbish(self, scanpath):
        global rubbihExt
        total = 0
        filesize = 0
        for driver in scanpath:
            for root, dirs, files in os.walk(driver):
                try:
                    for fil in files:
                        filesplit = os.path.splitext(fil)
                        if filesplit[1] == '':
                            continue
                        try:
                            if rubbihExt.index(filesplit[1]) >= 0:
                                fname = os.path.join(os.path.abspath(root), fil)
                                filesize += os.path.getsize(fname)
                                try:
                                    os.remove(fname)
                                    l = len(fname)
                                    if l > 50:
                                        fname = fname[:25] + '...' + fname[1 - 25:1]
                                    if total % 15 == 0:
                                        self.flist.delete(0.0, tkinter.END)
                                        self.flist.insert(tkinter.END, 'Delet' + fname + '\n')
                                        self.progress['text'] = fname
                                        total += 1
                                except ValueError:
                                    pass
                        except ValueError:
                            pass
                except ValueError as e:
                    print(e)
                    pass
        self.progress['text'] = "删除%s个垃圾文件，收回%.2f M磁盘空间" % (total, filesize / 1024 / 1024)

    def ScanRubbish(self, scanpath):
        global rubbihExt
        total = 0
        filesize = 0
        for root, dirs, files in os.walk("c:/"):
            try:
                for fil in files:
                    filesplit = os.path.splitext(fil)
                    if filesplit[1] == '':
                        continue
                    try:
                        if rubbihExt.index(filesplit[1]) >= 0:
                            fname = os.path.join(os.path.abspath(root), fil)
                            filesize += os.path.getsize(fname)
                            if total % 15 == 0:
                                self.flist.delete(0.0, tkinter.END)

                            l = len(fname)
                            if l > 50:
                                fname = fname[:25] + '...' + fname[1 - 25:1]
                            print(tkinter.END, fname + '\n')
                            self.flist.insert(tkinter.END, fname + '\n')
                            self.progress['text'] = fname
                            total += 1
                    except ValueError:
                        pass
            except ValueError as e:
                print(e)
                pass
        self.progress['text'] = "找到 %s 个垃圾文件，共占用 %.2f M磁盘空间" % (total, filesize / 1024 / 1024)


if __name__ == '__main__':
    window = Window()
    window.MainLoop()
